<template>
  <el-card class="!border-none" shadow="never">
    <div id="container"></div>
  </el-card>
</template>

<script>
import { onMounted } from 'vue'

export default {
  name: 'MapComponent',
  setup() {
    const latitude = 22.78223
    const longitude = 108.473192
    const urlICON = new URL('../../assets/images/light.png', import.meta.url)
      .href

    onMounted(() => {
      console.log('Icon URL:', urlICON) // 打印图片路径以确认正确性
      loadAMapScript(() => {
        initializeMap(latitude, longitude)
      })
    })

    function loadAMapScript(callback) {
      const existingScript = document.getElementById('amap-script')
      if (!existingScript) {
        const script = document.createElement('script')
        script.id = 'amap-script'
        script.type = 'text/javascript'
        script.src =
          'https://webapi.amap.com/maps?v=1.4.8&key=08ee87a833b939671a19fed3568a0823'
        script.onload = callback
        document.head.appendChild(script)
      } else {
        callback()
      }
    }

    function initializeMap(lat, lng) {
      const map = new AMap.Map('container', {
        zoom: 15,
        center: [lng, lat],
      })

      const marker = new AMap.Marker({
        position: new AMap.LngLat(lng, lat),
        title: '位置标题',
        icon: new AMap.Icon({
          image: urlICON,
          size: new AMap.Size(32, 32),
          imageSize: new AMap.Size(32, 32), // 设置图标大小
          imageOffset: new AMap.Pixel(0, 0), // 调整偏移量
        }),
      })

      map.add(marker)

      marker.on('click', function () {
        console.log('Marker clicked!')
      })
    }

    return {}
  },
}
</script>

<style scoped>
#container {
  width: 100%;
  height: 500px;
}
</style>
